<template>
  <view class="page-wrap">
    <public-header title="商品管理"></public-header>
    <view class="main-view">
      <view class="left-view    text-center">
        <view class="button-box flex justify-between margin-bottom">
          <button class="button normalsize line-white text-black" @click="clearClassify">全部商品</button>
          <view class="">
            <button class="button normalsize light text-black  margin-right" @click="addClassify">
              <text class="cuIcon-roundaddfill add-icon"></text> 新增分类
            </button>
          </view>
        </view>
        <view class="tree-box">
          <m-tree class="u-p-l-40" ref="mtree" :defaultProps="defaultProps" :data="classify" :lazyLoad="false"
            :divider="divider" :edit="edit" :unfold="true" @node-click="nodeClick" @add-item="addNode"
            @edit-item="editNode" @delete-item="deleteClassify">
          </m-tree>
        </view>
      </view>
      <view class="right-view ">
        <table-content :service="service" :filterData="filterData" :app="app" :include-columns="columns"
          :default-condition="setConditions" ref="goodsTable" @delete="deleteGoods">
          <template v-slot:tableFilter="tableFilter">
            <view class="table-filter">
              <view class="filter-form">
                <a-form v-if="isArray(tableFilter.columns)&&tableFilter.columns.length>0" :fields="tableFilter.columns"
                  :srvApp="'retail'" pageType="filter" ref="tableFilter" @value-blur="onfilterValueChange">
                </a-form>
              </view>
            </view>
          </template>
          <template #tableHandler="tableData">
            <button class="margin-right-lg button" @click="toFilter">查询</button>
            <button class="margin-right-3xl button light" @click="resetFilter()">重置</button>
          </template>
          <template #tableHandlerRight="tableData">
            <!-- <button class="button light" @click="batchHandler('打印',tableData)">批量打印</button> -->
            <button class="  button light" @click="batchHandler('上下架',tableData)">
              <image src="/static/icons/sxj.png" mode="aspectFit" class="icon margin-right"></image> 批量上下架
            </button>
          </template>
        </table-content>
      </view>
    </view>
    <view class="custom-center-popup">
      <u-popup :show="popupName==='add-classify'" :round="20" mode="center" :overlay="true" :closeable="false"
        :closeOnClickOverlay="false" @close="closePopup">
        <view class="remark-view">
          <view class="popup-title">
            新增分类
          </view>
          <bx-form serviceName="srvretail_goods_classify_add" type="add" @on-submit="addClassifySuccess()"
            @cancel="closePopup"></bx-form>
        </view>
      </u-popup>

      <u-popup :show="popupName==='batch-updown'" :round="20" mode="center" :overlay="true" :closeable="true"
        :closeOnClickOverlay="true" @close="closePopup">
        <view class="">
          <view class="popup-title">
            批量上下架
          </view>
          <batchUpdate :columns="srvCols" @cancel="closePopup" @confirm="onBatchUpdate"></batchUpdate>
        </view>
      </u-popup>
    </view>
  </view>
</template>

<script>
  import {
    deleteGoods,
    getClassify,
    updateClassify,
    deleteClassify
  } from '@/common/api/goods.js'
  import batchUpdate from '@/pages/main/components/batch-update-state.vue'
  // import batchUpdate from '@/pages/main/components/batch-update.vue'
  import lockscreen from '@/common/mixins/lockscreen.js'
  export default {
    components: {
      batchUpdate
    },
    mixins: [lockscreen],
    computed: {
      setConditions() {
        return [...this.classifyConditions || [], ...this.filterConditions || []]
      }
    },
    data() {
      return {
        filterData: null,
        popupName: "",
        mainData: {},
        columns: [
          'goods_name', 'goods_image', 'goods_barcode', 'sale_price', 'goods_stock', 'valuation_mode',
          'goods_unit',
          'goods_type',
          'sale_state'
        ],
        srvCols: [],
        filterCols: ['goods_name', 'sale_state'],
        app: "retail",
        service: "srvretail_goods_info_select",
        classify: [],
        /* 
         tree 数据
         */
        defaultProps: {
          id: 'no', // 此项为id项的key
          children: 'children', // 此项为修改子集数据的key
          label: 'classify_name' // 此项为修改显示数据的key
        },
        classifyConditions: [],
        filterConditions: [],
        divider: false,
        edit: true,
        checked: []
      };
    },
    onShow() {
      this.$refs?.goodsTable?.refresh()
      this.getClassify()
    },
    onLoad() {
      // this.getClassify()
    },

    methods: {

      onBatchUpdate(e) {
        // 批量编辑
        this.closePopup()
        let req = this.checked.map(item => {
          const obj = {
            "serviceName": "srvretail_goods_info_update",
            "condition": [{
              "colName": "id",
              "ruleType": "eq",
              "value": item.id
            }],
            "data": [{
              [e.column]: e.value
            }]
          }
          return obj
        })
        const url = `/retail/operate/srvretail_goods_info_update`
        uni.showModal({
          title: '提示',
          content: `确认将选中数据的售卖状态修改为${e.value}?`,
          success: (res) => {
            if (res.confirm) {
              this.$http.post(url, req).then(res => {
                uni.showToast({
                  title: res?.data?.resultMessage
                })
                this.$refs?.goodsTable?.clearCheck()
                this.toFilter()
              })
            }
          }
        })
        console.log(e);
        this.checked = []
      },
      // 批量操作
      batchHandler(type, e) {
        console.log(type, e);
        if (Array.isArray(e?.checked) && e?.checked.length > 0) {
          this.checked = e.checked
          if (e?.columns) {
            this.srvCols = e.columns
          }
          if (type === '打印') {
            uni.showToast({
              title: '开发中...',
              icon: 'none'
            })
          } else if (type === '上下架') {
            this.popupName = 'batch-updown'
          }
        } else {
          uni.showModal({
            title: '提示',
            content: '请先在左侧勾选要操作的数据',
            showCancel: false
          })
        }

      },
      clearClassify() {
        this.$refs?.mtree?.onClickItem?.()
      },
      closePopup() {
        this.popupName = ''
      },
      deleteGoods(ids) {
        if (ids && (typeof ids == 'string' || typeof ids == 'number')) {
          uni.showModal({
            title: '提示',
            content: '确认删除？',
            success: (res) => {
              if (res.confirm) {
                deleteGoods(ids).then(res => {
                  if (res === true) {
                    this.$refs?.goodsTable?.refresh()
                  }
                })
              }
            }
          })
        }
      },
      toFilter() {
        this.$nextTick(() => {
          this.$refs?.goodsTable?.onFilter?.(this.filterData)
        })
      },
      resetFilter() {
        this.$nextTick(() => {
          this.$refs?.tableFilter?.onReset()
          this.toFilter()
        })
      },
      onfilterValueChange() {
        let data = this.$refs?.tableFilter?.getFieldModel?.()
        if (data.sale_state == '全部') {
          data.sale_state = ''
        }
        this.filterData = data
      },
      addClassifySuccess() {
        this.getClassify()
        this.popupName = ''
      },
      // 跳转到新增节点页面
      addClassify() {
        this.popupName = 'add-classify'
      },

      //遍历id节点添加子项
      addNodeData(datas, id, nodedata) { //遍历树  获取id数组
        var addflag = false;
        if (id === 0) {
          datas.unshift(nodedata);
          addflag = true;
        } else {
          for (var i in datas) {
            console.log(JSON.stringify(datas[i]));
            if (id === datas[i].id) {
              // datas.push(datas[i]);
              console.log('要增加项目：', datas[i].id, nodedata);
              datas[i].children.unshift(nodedata);
              addflag = true;
              break;
            } else {
              if (datas[i].children) { //存在子节点就递归
                this.addNodeData(datas[i].children, id, nodedata);
              }
            }
          }
        }
        return addflag;
      },
      async deleteClassify(e) {
        if (e?.path) {
          const classifyConditions = [{
            colName: 'classify_path',
            ruleType: 'like]',
            value: e.path
          }]
          uni.showLoading({
            title: '请稍后'
          })
          const goodsAmount = await this.getChildGoodsAmount(classifyConditions)
          uni.hideLoading()
          if (goodsAmount && goodsAmount > 0) {
            uni.showToast({
              title: '当前分类或者其子分类下还有商品,不能直接删除',
              duration: 3000,
              icon: 'none'
            })
          } else {
            this.deleteNode(e)
          }
        }
      },
      async getChildGoodsAmount(cond) {
        const url = `/${this.app}/select/${this.service}`;
        const req = {
          "serviceName": "srvretail_goods_info_select",
          "colNames": ["*"],
          "condition": [],
          "page": {
            "pageNo": 1,
            "rownumber": 1
          },
        }
        if (cond) {
          req.condition = cond
        }
        const res = await this.$http.post(url, req)
        if (res?.data?.page) {
          return res.data.page.total
        }
      },
      //节点点击事件
      nodeClick(e) {
        if (e) {
          this.classifyConditions = [{
            colName: 'classify_path',
            ruleType: 'like]',
            value: e.path
          }]
        } else {
          this.classifyConditions = []
        }

        this.$nextTick(() => {
          this.toFilter()
        })
      },

      //节点新增按钮点击事件
      addNode(e) {
        //e.pNodeData, e.addContent
        console.log('点击的项目add', JSON.stringify(e));
        // 根据自身需求，自行修改数据新增方法；
        // 可以配合异步请求 执行服务器删除操作
        let data = {};
        if (e.id === 0) {
          data = {
            id: this.tree.length + 1,
            pid: e.id,
            label: '新增节点',
            name: '新增节点',
            children: []
          }
        } else {
          data = {
            id: e.pNodeData.id + e.pNodeData.children.length + 100,
            pid: e.pNodeData.id,
            label: e.addContent,
            name: e.addContent,
            children: []
          }
        }
        if (data) {
          this.addNodeData(this.tree, e.pNodeData.id, data);
        }
      },
      //节点更新按钮点击事件
      editNode(e) {
        console.log('点击的项目edit', e);
        if (e?.pNodeData?.id) {
          updateClassify(e?.pNodeData?.id, {
            classify_name: e.editContent
          }).then(res => {
            if (Array.isArray(res)) {
              this.classify = res
            }
          })
        }
      },
      //节点删除按钮点击事件
      deleteNode(e) {
        console.log('点击的项目delete', JSON.stringify(e));
        if (e?.id) {
          uni.showModal({
            title: '提示',
            content: '确认删除？',
            success: (res) => {
              if (res.confirm) {
                deleteClassify(e.id).then(res => {
                  this.classify = res
                })
              }
            }
          })
        }
      },

      async getClassify() {
        uni.showLoading({
          title: '加载中'
        })
        let res = await getClassify()
        uni.hideLoading()
        if (Array.isArray(res)) {
          this.classify = res.map(item => {
            item = {
              ...item,
              name: item.no,
              pid: item.parent_no
            }
            return item
          })
        }
      },

    },
  }
</script>

<style lang="scss">
  .page-wrap {
    height: calc(100vh - var(--window-top) - var(--window-bottom));
    display: flex;
    flex-direction: column;
    font-size: $retail-font-size-sm;

    ::v-deep .uni-card {
      .uni-card__content {
        font-size: $retail-font-size-sm;
      }

      .uni-card__header .uni-card__header-content .uni-card__header-content-title {
        font-size: $retail-font-size-sm;
      }
    }

    ::v-deep .tree-item .head .head-1 .txt {
      font-size: $retail-font-size-sm;
    }

    ::v-deep .tree-item {
      .head-1 {
        display: flex;
        align-items: center;
      }

      .left-icon,
      .edit-icon {
        width: 4rem;
        height: 4rem;
      }

      .hidden {
        width: 4rem;
      }
    }
  }

  .popup-title {
    line-height: 6rem;
  }

  .main-view {
    font-size: 2.4rem;
    flex: 1;
    display: flex;
    width: 100vw;
    overflow: hidden;
    background-color: #F5F5F5;

    height: calc(100vh - var(--window-top) - var(--window-bottom) - var(--header-height));

    .left-view {
      width: 30%;
      overflow-y: auto;
      border-right: 1px solid #f1f1f1;
      display: flex;
      flex-direction: column;
      padding: 3rem;
      background-color: #FFF;
      margin-right: 2rem;

      .button-box {
        display: flex;

        .button {
          min-width: 16rem;
          text-align: center;
          height: 6rem;
          font-size: 2.2rem;
        }
      }

      .tree-box {
        flex: 1;
        background-color: #f5f5f5;
        border-radius: 1rem;
        padding: 2rem;
        overflow-y: scroll;
      }

      .tree-list {
        border: 1px solid #f1f1f1;
        padding: 20px;
        margin-top: 10px;
      }
    }

    .right-view {
      flex: 1;
      overflow-y: auto;
      display: flex;
      flex-direction: column;
      padding: 2rem;
      background-color: #fff;
      border-radius: 1rem;

      ::v-deep .checkbox__inner {
        transform: scale(1.2);
      }

      margin: 2rem;
      margin-left: 0;

      ::v-deep .zb-table {
        flex: 1;
        font-size: $retail-font-size-xs;
      }
    }

    .table-filter {
      display: flex;
      flex-wrap: wrap;

      ::v-deep .uni-select__input-box {
        // height: 5rem;
      }

      ::v-deep .uni-select {
        // height: 5rem;
        // padding: 0;
        // padding: $retail-button-padding-base;
      }

      ::v-deep .uni-select__input-placeholder {
        font-size: $retail-font-size-xs;
      }

      .filter-form {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        flex: 1;

        ::v-deep .a-form {
          flex-direction: row;
        }

        ::v-deep .a-form {
          flex-direction: row;
        }
      }

      .operate-box {
        padding: 0 2rem;
        display: flex;
        align-items: center;
      }


      .form-item {
        width: 50rem;
        display: flex;
        align-items: center;
        font-size: $retail-font-size-sm;

        input {
          font-size: $retail-font-size-sm;
        }

        padding: $retail-button-padding-base;

        .label {
          margin-right: 1rem;
          min-width: 10rem;
        }

        .input {
          border: 1px solid #f1f1f1;
          padding: $retail-button-padding-base;
        }
      }
    }
  }

  ::v-deep .bx-form {
    padding: 0;
    overflow: hidden;

    .a-form {
      min-height: 40vh;
    }
  }
</style>
